package com.wanshu.sys.service.impl;

import com.wanshu.sys.entity.SysRole;
import com.wanshu.sys.entity.SysUser;
import com.wanshu.sys.service.ISysRoleService;
import com.wanshu.sys.service.ISysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户细节服务实现
 * springSecurity 用户认证
 *
 * @author 张颖辉（zyh）
 * @version 1.0.0
 * @date 2023/06/10
 */
@Service //忘记这个注解，会报错：错误的凭证
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysRoleService sysRoleService;

    /**
     * 用户登录认证的具体方法
     * 必须post请求
     *
     * @param username 用户名
     * @return {@link UserDetails }
     * @throws UsernameNotFoundException 用户名没有发现异常
     * @author 张颖辉（zyh）
     * @date 2023/06/10
     * @version 1.0.0
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*   临时写死账户为 admin  123456 （废弃）
        if ("admin".equals(username)) {
            // 授权集合（要为用户绑定的角色集合）
            List<GrantedAuthority> list = new ArrayList<>();
            list.add(new SimpleGrantedAuthority("ADMIN")); //添加一个授权为 ADMIN角色
            // 密码模拟的是数据库查询出来的
            String passWord = "$2a$10$vBRyzbJozBzJ2SdTX8ZWjeIgBLEjZm1TFy8KeywHjI.4PHnVp94qq";
            UserDetails userDetails = new User("admin", passWord, list);
            return userDetails;
        }*/
        // 从数据库获取账户密码，为TokenLoginFilter提供验证依据
        List<SysUser> userList = sysUserService.queryByUserName(username);
        if (userList != null && userList.size() == 1) {
            //这里说明账号是存在的
            SysUser sysUser = userList.get(0);
            List<SysRole> roleList = sysRoleService.queryByUserId(sysUser.getUserId());
            // 授权集合（要为用户绑定的角色集合）
            List<GrantedAuthority> list = new ArrayList<>();
            if (roleList!=null){
                for (SysRole sysRole : roleList) {
                    list.add(new SimpleGrantedAuthority(sysRole.getRoleName())); //添加一个授权
                }
            }
            // 密码模拟的是数据库查询出来的
            UserDetails userDetails = new User(sysUser.getUsername(), sysUser.getPassword(), list);
            return userDetails;
        }

        return null;
    }
}
